package cn.sdormitory.common.utils;

import cn.hutool.extra.spring.SpringUtil;
import cn.sdormitory.basedata.entity.BStudent;
import cn.sdormitory.login.AppTeacherDetails;
import cn.sdormitory.login.BStudentDetails;
import cn.sdormitory.sys.entity.SysUser;
import cn.sdormitory.sys.service.SysUserRoleService;
import com.google.common.base.Objects;
import io.jsonwebtoken.lang.Assert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.List;

/**
 * ClassName: BeanUtils
 * Description: 获取当前登陆用户信息
 */
@Slf4j
public class SysUserUtils {
    private static final long DEPT_MANAGER_ROLE_ID = 2;

    public static boolean isDeptManager(){
        Long userId = getSysUserId();
        Assert.notNull(userId,"请登录或不是老师");
        SysUserRoleService sysUserRoleService = SpringUtil.getBean(SysUserRoleService.class);
        List<Long> roleIdList = sysUserRoleService.listRoleIdByUserId(userId);
        for (Long roleId : roleIdList) {
            if(Objects.equal(DEPT_MANAGER_ROLE_ID,roleId)) {
                return true;
            }
        }
        return false;
    }

    public static Long getSysUserId(){
        return getSysUser().getId();
    }

    public static SysUser getSysUser() {
        try {
            SecurityContext ctx = SecurityContextHolder.getContext();
            Authentication auth = ctx.getAuthentication();
            Object principal = auth.getPrincipal();
            if(principal instanceof SysUserDetails){
                SysUserDetails sysUserDetails = (SysUserDetails)principal;
                return sysUserDetails.getSysUser();
            }else if(principal instanceof AppTeacherDetails){
                AppTeacherDetails appTeacherDetails = (AppTeacherDetails)principal;
                return appTeacherDetails.getSysUser();
            }
        } catch (Exception e) {
            log.error("获取系统用户失败,创建个空sysUser返回 错误信息:{}",e.getMessage());
        }
        return new SysUser();
    }

    public static BStudent getStudentUser() {
        try {
            SecurityContext ctx = SecurityContextHolder.getContext();
            Authentication auth = ctx.getAuthentication();
            BStudentDetails memberDetails = (BStudentDetails) auth.getPrincipal();
            return memberDetails.getSysUser();
        } catch (Exception e) {
            return new BStudent();
        }
    }
}
